package cn.liccshop.core.service.shopBrowseRecord.controller;


import cn.liccshop.core.entity.ShopBrowseRecord;
import cn.liccshop.core.service.shopBrowseRecord.service.IShopBrowseRecordService;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.Result;
import cn.liccshop.sys.entity.UserElement;
import cn.liccshop.sys.exception.MySystemException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import cn.liccshop.sys.base.MyActionController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @description  前端控制器
 *
 * @author LiCC
 * @since 2019-05-25
 */
@RestController
@RequestMapping("/shopBrowseRecord")
public class ShopBrowseRecordController extends MyActionController<ShopBrowseRecord> {

    @Autowired
    private IShopBrowseRecordService liShopBrowseRecordService;

    @Override
    protected IService<ShopBrowseRecord> getLiService(){
        return liShopBrowseRecordService;
    }

    /**
     * 消费者用户获取最近三十天浏览记录
     * @return
     */
    @RequestMapping(value = "/infos")
    public Result getBrowseRecordInfos() throws MySystemException {
        UserElement userElement = getUserInfoByToken();
        String userId = userElement==null?null:userElement.getUserId();
        if (StringUtils.isBlank(userId)){
            throw new MySystemException("用户未登陆", Constants.UNAUTHEN);
        }
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now().minusDays(29), LocalTime.MIN);
        /** 删除所有用户30天前的数据 **/
        liShopBrowseRecordService.remove(new QueryWrapper<>(new ShopBrowseRecord()).lt("create_date", localDateTime));
        /** 获取用户浏览数据 按时间降序 **/
        List<ShopBrowseRecord> browseRecords = liShopBrowseRecordService.list(new QueryWrapper<>(new ShopBrowseRecord().setUserId(userId)).orderByDesc("create_date"));
        return new Result().setCode(Constants.OK).setData(browseRecords).setMessage("获取浏览记录成功");
    }
    /**
     * 通过UserId清空消费者用户浏览记录
     * @return
     */
    @RequestMapping(value = "/deleteByUserId")
    public Result deleteBorwseRecordInfosByUserId() throws MySystemException {
        UserElement userElement = getUserInfoByToken();
        String userId = userElement==null?null:userElement.getUserId();
        if (StringUtils.isBlank(userId)){
            throw new MySystemException("用户未登陆", Constants.UNAUTHEN);
        }
        liShopBrowseRecordService.remove(new QueryWrapper<>(new ShopBrowseRecord().setUserId(userId)));
        return new Result().setCode(Constants.OK).setMessage("清空浏览记录成功");
    }

}

